package com.dadaguai.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dadaguai.common.BusinessException;
import com.dadaguai.domain.UserInfo;
import com.dadaguai.domain.UserIntegralRecord;
import com.dadaguai.mapper.UserInfoMapper;
import com.dadaguai.service.UserIntegralRecordService;
import com.dadaguai.mapper.UserIntegralRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 王半仙
 * @description 针对表【user_integral_record(用户积分记录表)】的数据库操作Service实现
 * @createDate 2023-10-20 11:28:40
 */
@Service
public class UserIntegralRecordServiceImpl extends ServiceImpl<UserIntegralRecordMapper, UserIntegralRecord>
        implements UserIntegralRecordService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserIntegralRecordMapper userIntegralRecordMapper;

    /**
     * 修改用户积分
     *
     * @param user 目标用户
     * @param type   积分类型
     * @param value  值（正数为增，负数为减）
     * @throws BusinessException
     */
    @Transactional
    @Override
    public void changeUserIntegral(UserInfo user, Integer type, Integer value) throws BusinessException {
        int current = user.getCurrentIntegral() + value;
        int total = user.getTotalIntegral() + Math.abs(value);
        if (current < 0) {
            throw new BusinessException("积分不足", -1);
        }
        //更新用户积分
        userInfoMapper.updateUserIntegral(current,total,user.getUserId());

        //记录积分
        UserIntegralRecord userIntegralRecord = new UserIntegralRecord();
        userIntegralRecord.setIntegral(value);
        userIntegralRecord.setUserId(user.getUserId());
        userIntegralRecord.setOperType(type);
        userIntegralRecord.setCreateTime(new Date());
        userIntegralRecordMapper.insert(userIntegralRecord);
    }
}




